import json
import os
from ctypes import windll
import win32api
import win32con
import keyboard


# 执行操作
def startClick(x, y):
    windll.user32.SetCursorPos(x, y)
    # 点一次
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y)


print("Ctrl + F1~F12 记忆鼠标当前位置")
print("F1 ~ F12 触发点击")
print("Alt + F1 ~ F12 清除指定记忆")
print("Ctrl + 0 清除所有记忆")

# 首次运行
hasFile = os.path.isfile('setting.json')
setting = {}

if hasFile:
    # 读取配置
    with open('./setting.json', 'r', encoding='utf8') as fp:
        setting = json.load(fp)
else:
    # 生成默认文件
    with open('./setting.json', 'a', encoding='utf8') as fp:
        json.dump({}, fp, ensure_ascii=False)

# 输出配置
print(setting)


# 监听热键
class PrevKey:
    def __init__(self):
        self.name = None

    pass


prev_key = PrevKey()


def hookKeyDown(key):
    global prev_key
    global setting

    # Ctrl + F1~12
    if prev_key.name == 'ctrl' and key.event_type == 'down' and 58 < key.scan_code < 88:
        x, y = win32api.GetCursorPos()
        setting[key.name] = {'x': x, 'y': y}
        with open('./setting.json', 'w', encoding='utf8') as file:
            json.dump(setting, file, ensure_ascii=False)
            print(setting)

    # Alt + F1~12
    if prev_key.name == 'alt' and key.event_type == 'down' and 58 < key.scan_code < 88:
        if key.name in setting:
            setting.pop(key.name)
            with open('./setting.json', 'w', encoding='utf8') as file:
                json.dump(setting, file, ensure_ascii=False)
                print(setting)

    # Ctrl + 0
    if prev_key.name == 'ctrl' and key.event_type == 'down' and key.scan_code == 11:
        with open('./setting.json', 'w', encoding='utf8') as file:
            json.dump({}, file, ensure_ascii=False)
            setting = {}
            print(setting)

    # F1~F12
    if prev_key.name is None and key.event_type == 'down' and 58 < key.scan_code < 88:
        if key.name in setting:
            startClick(setting[key.name]['x'], setting[key.name]['y'])
            print(key.name, setting[key.name]['x'], setting[key.name]['y'], '点击一次')

    # 记录当前按键
    if key.event_type == 'down':
        prev_key = key

    # 弹起时 将上一个按键置空
    if key.event_type == 'up':
        prev_key = PrevKey()


keyboard.hook(hookKeyDown)
keyboard.wait()
